/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.assistx.search.index;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author zhao.xiong
 */
public class QueueTest {

    private static ThreadPoolExecutor pool ;
    static{
       pool=new ThreadPoolExecutor(10, 200, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
       pool.allowCoreThreadTimeOut(true);
    }

    private static void p(final BlockingQueue<String> workQueue) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < 1000; i++) {
                        workQueue.put(System.currentTimeMillis() + "," + new Random().nextInt(10000));
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(QueueTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    }

    private static void c(final BlockingQueue<String> workQueue) {

        while (true) {
            try {
                final String s = workQueue.take();
                System.out.println("consume==>" + s + ",queuesize-->" + workQueue.size());
                if(workQueue.isEmpty()){
                    return;
                }
                pool.execute(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            System.out.println(pool.getActiveCount()+","+pool.getPoolSize());
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(QueueTest.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
            } catch (InterruptedException ex) {
                Logger.getLogger(QueueTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void main(String args[]) throws InterruptedException {

        BlockingQueue<String> workQueue = new LinkedBlockingQueue<String>();
        p(workQueue);
        c(workQueue);
        
        Thread.sleep(20000);
         System.out.println(pool.getActiveCount()+","+pool.getPoolSize());
    }
}
